# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo

import sys
import requests

sys.path.append('..')

from util import save_to_json


def get_tick_price(info):
  return {'tick_size': info['priceIncrement']}


def get_tick_qty(info):
  return {
      'tick_size': info['sizeIncrement'],
      'min_size': info['minProvideSize'],
  }


def to_normal(currency):
  currency = currency.upper()
  if currency == 'BCH':
    return 'BCHABC'
  elif currency == 'BSV':
    return 'BCHSV'
  else:
    return currency


def to_expire(alias):
  type_map = {
      '0925': 'NEXT_QUARTER',
      '0626': 'QUARTER',
  }
  return type_map[alias]


def parse_spot_instrument_info(json_data, mea):
  result = []
  for info in json_data["result"]:
    if info['type'] != "spot":
      continue
    native_symbol = info['name']
    native_base = info['baseCurrency']
    native_quote = info['quoteCurrency']
    base = to_normal(native_base)
    quote = to_normal(native_quote)
    symbol = "%s-%s" % (base, quote)

    product = {
        'mea': mea,
        'symbol': symbol,
        'native_symbol': native_symbol,
        'base': base,
        'native_base': native_base,
        'quote': quote,
        'native_quote': native_quote,
    }
    tick_info = {
        'tick_price': get_tick_price(info),
        'tick_qty': get_tick_qty(info),
    }
    product_info = {
        'product': product,
        'tick_info': tick_info,
    }
    '''
    toml_info = get_fee_rate(mea)

    fee_info = {
        'maker_fee_rate': toml_info['maker_fee_rate'],
        'taker_fee_rate': toml_info['taker_fee_rate'],
    }
    product_info['fee_info'] = fee_info
    '''
    result.append(product_info)
  return result


def parse_futures_instrument_info(json_data, mea):
  result = []
  for info in json_data["result"]:
    if not info['name'][-4:].isdigit():
      continue
    native_symbol = info['name']
    native_base = info['underlying']
    native_quote = 'USD'
    base = to_normal(native_base)
    quote = to_normal(native_quote)
    try:
      symbol = "%s-%s.%s" % (base, quote, to_expire(info['name'][-4:]))
    except Exception:
      print("can't pass future type: %s" % info['name'])
      continue

    product = {
        'mea': mea,
        'symbol': symbol,
        'native_symbol': native_symbol,
        'base': base,
        'native_base': native_base,
        'quote': quote,
        'native_quote': native_quote,
    }
    tick_info = {
        'tick_price': get_tick_price(info),
        'tick_qty': get_tick_qty(info),
    }
    product_info = {
        'product': product,
        'tick_info': tick_info,
    }
    '''
    toml_info = get_fee_rate(mea)

    fee_info = {
        'maker_fee_rate': toml_info['maker_fee_rate'],
        'taker_fee_rate': toml_info['taker_fee_rate'],
    }
    product_info['fee_info'] = fee_info
    # product_info['is_inverse'] = (info['is_inverse'] == 'true')
    # product_info['contract_value'] = float(info['contract_val'])
    '''
    result.append(product_info)
  return result


def parse_swap_instrument_info(json_data, mea):
  result = []
  for info in json_data["result"]:
    if not info['name'].endswith("-PERP"):
      continue
    native_symbol = info['name']
    native_base = info['underlying']
    native_quote = 'USD'
    base = to_normal(native_base)
    quote = to_normal(native_quote)
    symbol = "%s-%s.PERPETUAL" % (base, quote)

    product = {
        'mea': mea,
        'symbol': symbol,
        'native_symbol': native_symbol,
        'base': base,
        'native_base': native_base,
        'quote': quote,
        'native_quote': native_quote,
    }
    tick_info = {
        'tick_price': get_tick_price(info),
        'tick_qty': get_tick_qty(info),
    }
    product_info = {
        'product': product,
        'tick_info': tick_info,
    }
    '''
    toml_info = get_fee_rate(mea)

    fee_info = {
        'maker_fee_rate': toml_info['maker_fee_rate'],
        'taker_fee_rate': toml_info['taker_fee_rate'],
    }
    product_info['fee_info'] = fee_info
    product_info['is_inverse'] = (info['is_inverse'] == 'true')
    product_info['contract_value'] = float(info['contract_val'])
    '''
    result.append(product_info)
  return result


def main():
  spot_url = 'https://ftx.com/api/markets'
  data = requests.get(spot_url).json()
  mea = 'Spot.Ftx.v1'
  product_info1 = parse_spot_instrument_info(data, mea)

  futures_url = 'https://ftx.com/api/markets'
  data = requests.get(futures_url).json()
  mea = 'Futures.Ftx.v1'
  product_info2 = parse_futures_instrument_info(data, mea)

  swap_url = 'https://ftx.com/api/markets'
  data = requests.get(swap_url).json()
  mea = 'Futures.Ftx.v1-swap'
  product_info3 = parse_swap_instrument_info(data, mea)

  product_info = product_info1 + product_info2 + product_info3
  product_info = sorted(product_info, key=lambda x: x['product']['symbol'])
  bundle = {
      "exchange": 'Ftx',
      "each_product_info": product_info,
  }
  save_to_json(bundle, 'product_info.json')


if __name__ == '__main__':
  main()
